package com.haierp.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.wangzhixuan.commons.utils.StringUtils;

import net.sf.json.JSONObject;

public class DimensionCodeUtil {
	public static String youZanToken;
	public static String clientId;
	public static String clientSecret;
	public static String kdtId;
	
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}
	
	public static void setClientKey(String clientIdP, String clientSecretP, String kdtIdP) {
		clientId = clientIdP;
		clientSecret = clientSecretP;
		kdtId = kdtIdP;
	}
	
	// 获取有赞token 
	public static void getYouZanToken(){
		String  urlresponse = DimensionCodeUtil.sendGet("https://open.youzan.com/oauth/token", "client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=silent&kdt_id=" + kdtId);
		JSONObject jsonObject = JSONObject.fromObject(urlresponse);
		youZanToken = jsonObject.getString("access_token");
		System.out.println("第一次获取youZanToken:" + youZanToken);
	}

	//参数名的值默认升序
	public static String getSign(Map<String, String> params) {
		Map<String, String> sortMap = new TreeMap<String, String>();
		sortMap.putAll(params);
		// 以k1=v1&k2=v2...方式拼接参数
		StringBuilder builder = new StringBuilder();
		for (Map.Entry<String, String> s : sortMap.entrySet()) {
			String k = s.getKey();
			String v = s.getValue();
			if (StringUtils.isBlank(v)) {// 过滤空值
				continue;
			}
			builder.append(k).append("=").append(v).append("&");
		}
		if (!sortMap.isEmpty()) {
			builder.deleteCharAt(builder.length() - 1);
		}
		String  no = builder.toString();
		return Md5Util.getMD5(builder.toString());
	}

	//参数名的值默认升序
	public static String getParamsSort(Map<String, String> params) {
		Map<String, String> sortMap = new TreeMap<String, String>();
		sortMap.putAll(params);
		// 以k1=v1&k2=v2...方式拼接参数
		StringBuilder builder = new StringBuilder();
		for (Map.Entry<String, String> s : sortMap.entrySet()) {
			String k = s.getKey();
			String v = s.getValue();
			if (StringUtils.isBlank(v)) {// 过滤空值
				continue;
			}
			builder.append(k).append("=").append(v).append("&");
		}
		if (!sortMap.isEmpty()) {
			builder.deleteCharAt(builder.length() - 1);
		}
		String  no = builder.toString();
		return no;
	}

	//精确到秒级别
	public static Integer getSecondTimestamp(Date date){
		if (null == date) {
			return 0;
		}
		String timestamp = String.valueOf(date.getTime());
		int length = timestamp.length();
		if (length > 3) {
			return Integer.valueOf(timestamp.substring(0,length-3));
		} else {
			return 0;
		}
	}

	public static String redBookHttpRequest(String path,Map<String, String> params, String method,String type) throws Exception{
		String appKey = "";
		String appSecret = "";
		if("SL".equals(type)) {
			appKey =PropertiesUtils.getProperties().getProperty("xiaohongshubag.appKey");
			appSecret = PropertiesUtils.getProperties().getProperty("xiaohongshubag.appSecret");
		} else {
			appKey =PropertiesUtils.getProperties().getProperty("xiaohongshu.appKey");
			appSecret = PropertiesUtils.getProperties().getProperty("xiaohongshu.appSecret");
		}
		Integer timestamp = DimensionCodeUtil.getSecondTimestamp(new Date());
		Map<String,String> paramMap = new HashMap<>();
		paramMap.put("timestamp",timestamp.toString());
		paramMap.put("app-key",appKey);
		if("GET".equals(method) ) {
			paramMap.putAll(params);	
		}
		String pathString = path+"?"+DimensionCodeUtil.getParamsSort(paramMap);
		String md5 = Md5Util.getMD5(pathString+appSecret);
		Map<String,String> header = new HashMap<>();
		header.put("timestamp",timestamp.toString());
		header.put("app-key",appKey);
		header.put("sign",md5);
		Map<String,Object> param = new HashMap<>();
		param.putAll(params);
		String string = null;
		if("POST".equals(method)) {
			string = HttpClientUtil.post("https://ark.xiaohongshu.com"+path, header, param, "2", "2");
		} else if("PUT".equals(method)){
		    string = HttpClientUtil.put("https://ark.xiaohongshu.com"+path, header, param, "1", "2");
		} else {
			string = HttpClientUtil.get("https://ark.xiaohongshu.com"+path, header, param, "2", "2");
		}
		return string;
	}

}